#coding:utf-8
from django import forms
from django.contrib import admin
from django.template import RequestContext
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from lovewith.share.models import *


#分享管理
class PostAdmin(admin.ModelAdmin):
    list_display = ('id', 'cate', 'title', 'post_date', 'user', 'edit_share')
    ordering = ('-post_date',)
    #添加快速查询栏
    search_fields = ('title',)
    #过滤器
    list_filter = ('cate', 'user')
    actions = ('updateCategory',)


    def get_actions(self, request):
        actions = super(PostAdmin, self).get_actions(request)
        del actions['delete_selected']
        return actions

    def delete_model(self, request, obj):
        for o in obj.all():
            o.delete()

    delete_model.short_description = 'Delete flow'

    def edit_share(self, obj):
        return '<a href="/share/edit/%s" target="_blank">编辑</a>' % obj.id

    edit_share.short_description = '编辑'
    edit_share.allow_tags = True

    #批量修改分类
    class CategoryForm(forms.Form):
        _selected_action = forms.CharField(widget=forms.MultipleHiddenInput)
        category = forms.ModelChoiceField(Category.objects)

    def updateCategory(self, request, queryset):
        form = None
        if 'cancel' in request.POST:
            self.message_user(request, u'取消')
            return
        elif 'category' in request.POST:
            form = self.CategoryForm(request.POST)
            if form.is_valid():
                category = form.cleaned_data['category']
                for link in queryset:
                    link.cate = category
                    link.save()

                self.message_user(request, "%s 条灵感分类修改成功" % queryset.count())
                return HttpResponseRedirect(request.get_full_path())

        if not form:
            form = self.CategoryForm(initial={'_selected_action': request.POST.getlist(admin.ACTION_CHECKBOX_NAME)})
        return render_to_response('admin/batch_update.html', {
            'form': form,
            'path': request.get_full_path(),
            'action': 'updateCategory',
            'title': u'批量修改分类'
        }, context_instance=RequestContext(request))

    updateCategory.short_description = u'批量修改分类'


#来源管理
class PostOrignAdmin(admin.ModelAdmin):
    list_display = ('id', 'role', 'orign_user', 'adddate')
    ordering = ('-id',)
    #只读字段(django后台的外键显示有性能问题所以需要禁用某些字段)
    readonly_fields = ('add_user', 'orign_user', 'add_date')
    #分页
    list_per_page = 50

    def role(self, obj):
        return obj.user_role.name

    role.short_description = '角色'

    def adddate(self, obj):
        return obj.add_date.strftime('%Y/%m/%d %H:%M:%S')
    adddate.short_description = '添加时间'


#打标商品管理
class AttachGoodsAdmin(admin.ModelAdmin):
    list_display = ('id', 'user', 'image', 'product', 'product_price', 'tagname', 'adddate')
    ordering = ('-id',)
    #分页
    list_per_page = 50
    #只读字段(django后台的外键显示有性能问题所以需要禁用某些字段)
    readonly_fields = ('user', 'post_image', 'flag_position', 'post_date')
    actions = ('updateTag',)

    #显示图片预览
    def image(self, obj):
        img_path = ''
        if obj.post_image.path.find('http') < 0:
            img_path = 'http://img.lovewith.me/upload/share/%s' % obj.post_image.path.replace('_650x999', '_100x100')
        else:
            img_path = '%s!100' % obj.post_image.path

        return '<a href="/share/detail/%s/?mid=%s" target="_blank"><img src="%s" width="100" /></a>' % (
            obj.post_image.share_post.id, obj.post_image.id, img_path)


    image.short_description = '预览图片(点击查看原帖)'
    image.allow_tags = True

    #添加产品的淘宝链接
    def product(self, obj):
        return '<a href="%s" target="_blank">%s</a>' % (obj.product_url, obj.product_name)

    product.short_description = '产品详情'
    product.allow_tags = True

    def adddate(self, obj):
        return obj.post_date.strftime('%Y/%m/%d %H:%M:%S')

    adddate.short_description = '添加时间'

    def updateTag(self, request, queryset):
        if 'cancel' in request.POST:
            self.message_user(request, u'取消')
            return
        elif 'tagname' in request.POST:
            for link in queryset:
                link.tagname = request.POST.get('tagname')
                link.save()

            self.message_user(request, "%s 条灵感标签修改成功" % queryset.count())
            return HttpResponseRedirect(request.get_full_path())

        tag_data = []
        cate_filter_data = GoodsTag.objects.all()
        for data in cate_filter_data:
            #替换中文逗号
            tag = data.tags.replace('，', ',').split(',')
            tag_data.extend(tag)

        return render_to_response('admin/goods_update_tag.html', {
            'tag_data': tag_data,
            'path': request.get_full_path(),
            'action': 'updateTag',
            'title': u'批量修改标签',
            'selected_action': request.POST.getlist(admin.ACTION_CHECKBOX_NAME)
        }, context_instance=RequestContext(request))
    updateTag.short_description = u'批量修改标签'


#预设关键词管理
class MtPresetTagAdmin(admin.ModelAdmin):
    list_display = ('tag', 'related_tag')

    def related_tag(self, obj):
        return '%s...' % obj.tag_related[0:200]

    related_tag.short_description = '关联标签'

#注册显示model
admin.site.register(Post, PostAdmin)
admin.site.register(PostOrign, PostOrignAdmin)
admin.site.register(AttachGoods, AttachGoodsAdmin)
admin.site.register(MtPresetTag, MtPresetTagAdmin)